package org.tea.inventory.admin.web.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tea.inventory.admin.web.admin.BaseController;
import org.tea.inventory.base.exception.ApplicationException;
import org.tea.inventory.base.response.BaseResponse;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.base.util.excel.ExportExcel;
import org.tea.inventory.domain.tea.ProductCategory;
import org.tea.inventory.service.IProductCategoryService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dongxb
 * @description 商品类型控制器
 * @date 2025年04月03日 09:00
 */
@Api(tags = "商品管理-商品类别控制器")
@Slf4j
@RestController
@RequestMapping("/admin/product-category")
@RequiredArgsConstructor
public class ProductCategoryController extends BaseController {

    private final IProductCategoryService productCategoryService;

    /**
     * 获取商品类别列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取商品类别列表")
    @ApiResponses(
            @ApiResponse(code = 0 , message = "成功" , response = ProductCategory.class)
    )
    public BaseResponse list(ProductCategory productCategory) {
        log.info("productCategory=" + productCategory.toString());
        List<ProductCategory> types = productCategoryService.selectProductCategoryList(productCategory);
        return ResponseUtil.ok(types);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/excludeChild")
    @ApiOperation(value = "查询商品类别列表（排除节点）")
    @ApiResponses(
            @ApiResponse(code = 0, message = "成功", response = ProductCategory.class)
    )
    public BaseResponse excludeChild(Long id) {
        List<ProductCategory> productCategories = productCategoryService.selectProductCategoryList(new ProductCategory());
        productCategories.removeIf(d -> d.getId().intValue() == id);
        return ResponseUtil.ok(productCategories);
    }

    @GetMapping(value = "/getInfo")
    @ApiOperation(value = "根据商品类别编号获取详细信息")
    @ApiResponses(
            @ApiResponse(code = 0, message = "成功", response = ProductCategory.class)
    )
    public BaseResponse getInfo(Long id) {
        return ResponseUtil.ok(productCategoryService.selectByPrimaryKey(id));
    }

    /**
     * 新增商品类别
     */
    @PostMapping(value = "/add")
    @ApiOperation(value = "新增商品类别")
    public BaseResponse add(@Validated @RequestBody ProductCategory productCategory) {
        log.info("productCategory=" + productCategory.toString());
        if (!productCategoryService.checkCategoryIdUnique(productCategory)) {
            log.error("类别编号唯一校验失败");
            throw  new ApplicationException(-1,"新增商品类型失败，商品类型编号" + productCategory.getCategoryCode() + "已存在");
        }
        return ResponseUtil.ok(productCategoryService.insertProductCategory(productCategory));
    }

    /**
     * 删除商品类别
     */
    @PostMapping(value = "/remove")
    @ApiOperation(value = "删除商品类别")
    public BaseResponse remove(Long id) {
        if (productCategoryService.hasChildById(id)) {
            log.error("存在下级商品类型,不允许删除");
            throw  new ApplicationException(-1,"存在下级商品类型,不允许删除");
        }
        return ResponseUtil.ok(productCategoryService.deleteById(id));
    }

    /**
     * 修改商品类别
     */
    @PostMapping(value = "/edit")
    @ApiOperation(value = "修改商品类别")
    public BaseResponse edit(@RequestBody @Validated ProductCategory productCategory) {
        log.info("productCategory=" + productCategory.toString());
        if (!productCategoryService.checkCodeUpdate(productCategory)) {
            log.error("类别编号唯一校验失败");
            throw  new ApplicationException(-1,"修改商品类型失败，商品类型编号" + productCategory.getCategoryCode() + "已存在");
        }

        return ResponseUtil.ok(productCategoryService.update(productCategory));
    }

    /**
     * 导出商品类别
     */
    @GetMapping("/export/category")
    @ApiOperation(value = "导出商品类别列表")
    public void exportProductCategory(ProductCategory productCategory, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        String title = "商品类别列表";
        String header = "类别编号,类别名称,父类别编号,父类别名称,创建时间";
        String column = "categoryCode,categoryName,categoryParentCode,categoryParentName,createDateStr";
        map.put("biaoti", title);
        map.put("header", header);
        map.put("column", column);
        try {
            List<ProductCategory> productCategories = productCategoryService.selectProductCategoryList(productCategory);
            List<Map> list = JSONArray.parseArray(JSON.toJSONString(productCategories), Map.class);
            ExportExcel.export(request, response, list, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
